import { WHITE_LIST } from '../index';
import { getToken } from '@/utils/auth';
import { isHttp } from '@/utils/validate';
import useUserStore from '@/store/modules/user';
import useSettingsStore from '@/store/modules/settings';
import usePermissionStore from '@/store/modules/permission';
import type { Router } from 'vue-router';

export function createPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore();
    const name: string = (to.name ?? '') as string;
    // 将admin状态存储到session或其他地方，而不是直接修改路由对象
    to.meta?.title && useSettingsStore().setTitle(to.meta.title);
    if (to.path === '/login') {
      next();
      return;
    }

    // 已经登录
    if (getToken() && to.meta.isAdmin) {
      /* has token*/
      if (!userStore.roles.length || !userStore.userInfo.userId) {
        try {
          await userStore.getInfo();
          const accessRoutes: any = await usePermissionStore().generateRoutes();
          // 根据roles权限生成可访问的路由表
          accessRoutes.forEach((route) => {
            if (!isHttp(route.path)) {
              router.addRoute(route); // 动态添加可访问路由表
            }
          });
          next({ ...to, replace: true });
        } catch (e) {
          await userStore.logOut();
          if (to.meta.isAdmin) {
            next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
          } else {
            // 前台未登录
            next();
          }
        }
      } else {
        next();
      }
    } else if (
      WHITE_LIST.indexOf(to.path) !== -1 ||
      WHITE_LIST.indexOf(name) !== -1 ||
      to.meta?.requiresAuth === false ||
      to.meta?.isAdmin === false
    ) {
      // 在免登录白名单，直接进入
      next();
    } else {
      if (to.meta.isAdmin) {
        next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
      } else {
        next();
      }
    }
  });
}
